package holiday.mae.app;

import mae.app.R;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;


public class HolidayPiece extends Activity {

		private HolidayHelper dbHolidayHelper = null;
		private Cursor myCursor = null;
		private HolidayAdapter adapter = null;

		/** Called when the activity is first created. */
		@Override
		public void onCreate(Bundle savedInstanceState) {
			try {
				super.onCreate(savedInstanceState);
				setContentView(R.layout.piece);

				ListView myListView = (ListView) findViewById(R.id.list);

				dbHolidayHelper = new HolidayHelper(this,
						null, null, 0);

				dbHolidayHelper.createDatabase();

				dbHolidayHelper.openDatabase();

				myCursor = dbHolidayHelper.getCursor();

				startManagingCursor(myCursor);

				adapter = new HolidayAdapter(myCursor);

				myListView.setAdapter(adapter);
			} catch (Exception e) {
				Log.e("ERROR", "ERROR IN CODE: " + e.toString());
				e.printStackTrace();
			}
		}

		class HolidayAdapter extends CursorAdapter {
			HolidayAdapter(Cursor c) {
				super(HolidayPiece.this, c);
			}

			@Override
			public void bindView(View row, Context context, Cursor c) {
				HolidayHolder holder = (HolidayHolder) row
						.getTag();
				holder.populateFrom(c, dbHolidayHelper);
			}

			@Override
			public View newView(Context context, Cursor c, ViewGroup parent) {
				LayoutInflater inflater = getLayoutInflater();
				View row = inflater.inflate(R.layout.row, parent, false);
				HolidayHolder holder = new HolidayHolder(row);
				row.setTag(holder);
				return (row);
			}
		}

		static class HolidayHolder {
			private TextView piece = null;
			private TextView value = null;
			private EditText quanity = null;

			HolidayHolder(View row) {
				piece = (TextView) row.findViewById(R.id.pieceText);
				value = (TextView) row.findViewById(R.id.valueText);
				quanity = (EditText) row.findViewById(R.id.quanityText);
			}

			void populateFrom(Cursor c, HolidayHelper r) {
				piece.setText(r.getPiece(c));
				value.setText(r.getValue(c));
				quanity.setText(r.getQuanity(c));
			}
		}
	}